import { _decorator, Component, Label, Node, ProgressBar, tween, Tween } from 'cc';
import { DataMgr, PlayerData } from '../../Basic/Manager/DataManager';
import { GameParams, PlayerParams } from '../../Basic/Config/DataConfig';
import { VisitorItem } from './VisitorItem';
import { PoolFactory } from '../../Basic/Component/PoolFactory';
import { EventType, PoolElementType } from '../Config/GameEnum';
import { MathUtil } from '../../Util/MathUtil';
import { GameModel, SingleOrder } from './GameModel';
import { AudioManager } from '../../Basic/Manager/AudioManager';
import { SoundCode } from '../../Basic/Config/BaseEnum';
import { EventManager } from '../../Basic/Manager/EventManager';
import { GEEvent, GravityModel } from '../../Basic/Model/SDK/GravityModel';
const { ccclass, property } = _decorator;

@ccclass('OrderMachine')
export class OrderMachine extends Component {
  @property(Node)
  visitorParent: Node;
  @property(Node)
  coinParent: Node;
  @property(PoolFactory)
  poolFac: PoolFactory;
  @property(Label)
  coinLab: Label;

  @property(ProgressBar)
  levelBar: ProgressBar;
  @property(Label)
  levelRateLab: Label;
  visitorItems: VisitorItem[];
  maxVisitorCount: number;
  curVisitorOrder: number;
  visitorConfig: SingleOrder[];
  adVisitor: number;
  constructor() {
    super();
    this.visitorItems = [];
    this.maxVisitorCount = 0;
    this.curVisitorOrder = 0;
  }

  protected onEnable(): void {
    EventManager.Ins().register(EventType.AD_VISITOR, this.onVisitorAd, this);
  }

  protected onDisable(): void {
    EventManager.Ins().unRegister(EventType.AD_VISITOR, this.onVisitorAd);
  }

  /** 初始化顾客 */
  initVisitors() {
    this.visitorConfig = [];
    this.adVisitor = -1;
    const idArr = [];
    DataMgr.tables.TbColorLib.get(GameModel.Ins().curLibIndex).lib.forEach((id) => {
      idArr.push(id);
    });
    GameModel.Ins().curLevelData.visitor.forEach((visitor) => {
      this.maxVisitorCount += visitor.peopleCount;
      for (let i = 0; i < visitor.peopleCount; i++) {
        if (visitor.cake === 'random')
          this.visitorConfig.push({ cake: idArr[MathUtil.randomIntegerBetween(0, idArr.length)], count: MathUtil.randomIntegerBetween(visitor.count[0], visitor.count[0]) });
        else this.visitorConfig.push({ cake: visitor.cake, count: MathUtil.randomIntegerBetween(visitor.count[0], visitor.count[0]) });
      }
    });

    // Tool.shuffleArray(this.visitorConfig);

    // this.maxVisitorCount = GameModel.Ins().curLevelData.visitor.length;
    this.curVisitorOrder = 0;
    const level = DataMgr.gameParams.get(GameParams.gameLevel);
    const count = level == 1 ? 1 : 3;
    for (let i = 0; i < count; i++) {
      const item = this.poolFac.pop(PoolElementType.VISITOR_ITEM, 'maingame/game', 'VisitorItem');
      const script = item.getComponent(VisitorItem);
      script.reset();
      script.setData('', 0);
      script.setLockState(i);
      this.visitorItems.push(script);
      this.visitorParent.addChild(item);
      item.setPosition((-(count - 1) / 2) * 200 + i * 200, 0);
    }

    this.coinLab.string = `${GameModel.Ins().gameCoin}`;
    Tween.stopAllByTarget(this.levelBar);
    this.levelBar.progress = 0;
    this.levelRateLab.string = `0%`;

    this.refreshVisitorOrder();
  }

  resetVisitors() {
    while (this.visitorItems.length) {
      const item = this.visitorItems.pop();
      item.reset();
      this.poolFac.push(item.node);
    }
    this.visitorItems = [];
    this.maxVisitorCount = 0;
    this.curVisitorOrder = 0;
    Tween.stopAllByTarget(this.levelBar);
    this.levelBar.progress = 0;
  }

  refreshProgress() {
    Tween.stopAllByTarget(this.levelBar);
    let visitorRate = 0;
    this.visitorItems.forEach((visitor) => {
      if (visitor.btn_gold.active || visitor.btn_ad.active || visitor.curColor === '' || visitor.maxCount === 0) return;
      console.log(visitor.curCount, visitor.maxCount);

      visitorRate += 1 - visitor.curCount / visitor.maxCount;
    });
    const rate = (GameModel.Ins().finishOrder + visitorRate) / this.maxVisitorCount;
    this.levelRateLab.string = `${Math.floor(rate * 100)}%`;
    tween(this.levelBar).to(0.2, { progress: rate }).start();
  }

  /** 获取随机订单 */
  getRandomOrder() {
    const idArr = DataMgr.tables.TbColorLib.get(GameModel.Ins().curLevelData.colorLib).lib;
    return { cake: idArr[MathUtil.randomIntegerBetween(0, idArr.length)], count: MathUtil.randomIntegerBetween(1, 5) };
  }

  /** 获取所有需求颜色 */
  getVisitorColor() {
    const arr: string[] = [];
    this.visitorItems.forEach((visitor) => {
      if (visitor.curCount > 0 && visitor.curColor != '' && arr.indexOf(visitor.curColor) === -1) {
        arr.push(visitor.curColor);
      }
    });
    return arr;
  }

  /** 减少颜色需求 */
  reduceVisitorColor(colorArr: SingleOrder[]) {
    let ret = false;
    const tempArr = [...colorArr.splice(0)];
    const finishArr = [];
    for (let i = 0; i < tempArr.length; i++) {
      const data = tempArr[i];
      this.visitorItems.forEach((visitor, index) => {
        if (visitor.btn_gold.active || visitor.btn_ad.active) return;
        const tempCount = data.count;
        data.count = visitor.reduceCount(data.cake, data.count);
        if (tempCount > data.count) ret = true;

        if (ret && visitor.curColor != '' && visitor.curCount <= 0 && finishArr.indexOf(index) === -1) {
          GameModel.Ins().addFinishOrder(index);
          finishArr.push(index);
        }
      });
    }
    if (ret) {
      AudioManager.Singleton.playSound(SoundCode.JELLY_FLY);
      setTimeout(this.refreshVisitorOrder.bind(this), 500);
    }
  }

  /** 刷新客人订单 */
  refreshVisitorOrder() {
    console.log('refreshVisitorOrder');
    this.visitorItems.forEach((visitor) => {
      if (visitor.btn_gold.active || visitor.btn_ad.active) return visitor.refreshUI();
      if (visitor.curColor != '' && visitor.curCount <= 0) {
        // 完成订单
        console.log('完成订单');
        visitor.setData(``, 0);
        visitor.messageNode.active = false;
        // GameModel.Ins().addFinishOrder(i);
        visitor.animCtrl.playAni('Visitor_out');
      } else {
        let ref = true;
        if (visitor.curColor === '' && visitor.animCtrl.curState === 'Visitor_out' && !visitor.animCtrl.outting) {
          if (this.visitorConfig.length > 0) {
            const order = this.visitorConfig.shift();
            visitor.setData(order.cake, order.count);
            console.log('刷新订单');
            visitor.animCtrl.playAni('Visitor_in');
          } else {
            ref = false;
          }
        }
        // eslint-disable-next-line @typescript-eslint/no-unused-expressions
        ref && visitor.refreshUI();
      }
    });
    this.refreshProgress();
  }

  onVisitorAd(isVideo: boolean = true) {
    if (this.adVisitor < 0 || this.adVisitor >= this.visitorItems.length) return;
    if (this.visitorConfig.length > 0) {
      this.visitorItems[this.adVisitor].unlock();
      this.refreshVisitorOrder();
    } else {
      this.visitorItems[this.adVisitor].btn_gold.active = false;
      this.visitorItems[this.adVisitor].btn_ad.active = false;
    }
    this.adVisitor = -1;
    this.refreshProgress();
    if (isVideo) {
      GameModel.Ins().adCount++;
      DataMgr.changePlayerAttr(PlayerParams.adCount, 1);
      // GravityModel.I.userSet({ accuAds: PlayerData.get(PlayerParams.adCount) });
      // GravityModel.I.track(GEEvent.AD_SHOW_END, { adPosition: `看广告解锁顾客栏` });
    }
  }
}
